package com.scaffold.commons.spring;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.MutablePropertyValues;
import org.springframework.validation.BindException;
import org.springframework.validation.DataBinder;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import wangjg.commons.page.Page;
import wangjg.commons.page.WebPage;

import com.scaffold.commons.web.WebUtil;

/**
 * 
 * @author wangjg
 *
 */
public class BasicAction {
	
	protected Page getPage(Integer pageSize){
		Integer pageNo = 1;
		try{
			String pageNo_s = this.getRequest().getParameter("pageNo");
			if(pageNo_s!=null){
				pageNo = Integer.parseInt(pageNo_s);
			}
			String pageSize_s = this.getRequest().getParameter("pageSize");
			if(pageSize_s!=null){
				pageSize = Integer.parseInt(pageSize_s);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		
		WebPage page = new WebPage(pageSize, pageNo);
		return page;
	}

	/**
	 * 统一处理，还可以根据客户端类型做不同的处理。
	 * @return
	 */
	protected String getResult(String code, String message, Object data){
		HashMap<String,Object> result = new HashMap<String,Object>();
		result.put("code", code);
		if(message!=null){
			result.put("message", message);
		}
		if(data!=null){
			result.put("data", data);
		}
		this.getRequest().setAttribute("jsonMap", result);
		return "commons/json.vm";
	}

	protected void bindParams(Object bean){
		Map<String, String> params = this.getParameterMap();
		bindParams(bean, params, null, null);
	}
	
	protected void bindParams(Object bean, String...exclued){
		Map<String, String> params = this.getParameterMap();
		bindParams(bean, params, null, exclued);
	}
	
	@SuppressWarnings("rawtypes")
	protected static BindException bindParams(Object bean , Map map, String[] allowedFields ,String[] disallowedFields){
		DataBinder binder = new DataBinder(bean);
		if(allowedFields!=null && allowedFields.length>0){
			binder.setAllowedFields(allowedFields);
		}
		if(disallowedFields!=null && disallowedFields.length>0){
			binder.setDisallowedFields(disallowedFields);
		}
		MutablePropertyValues mpvs = new MutablePropertyValues(map);
		binder.bind(mpvs);
		BindException errors = new BindException(binder.getBindingResult());
		return errors;
	}

	protected Map<String, String> getParameterMap() {
		return WebUtil.getParameterMap(this.getRequest());
	}

	protected HttpServletRequest getRequest(){
		ServletRequestAttributes holder = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = holder.getRequest();
		return request;
	}
	
}
